﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace CiStatus.CiStatusAddIn.Logic
{
    public class SettingsFormatter : ISettingsFormatter
    {
        public string Serialize(IDictionary<KeyValuePair<string, string>, IDictionary<string, string>> value)
        {
            string returnString;
            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, value);
                returnString = new string(Encoding.GetEncoding("iso-8859-1").GetChars(stream.ToArray()));
            }

            return returnString;
        }

        public IDictionary<KeyValuePair<string, string>, IDictionary<string, string>> Deserialize(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(value);
                using (var stream = new MemoryStream(bytes))
                {
                    var formatter = new BinaryFormatter();
                    return (IDictionary<KeyValuePair<string, string>, IDictionary<string, string>>)formatter.Deserialize(stream);
                }
            }
            return  new Dictionary<KeyValuePair<string, string>, IDictionary<string, string>>();
        }
    }
}